package com.onpositive.realmview.queryeditor;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.Platform;

import com.onpositive.realmview.AbstractRealmView;
import com.onpositive.realmview.IRealmView;
import com.onpositive.realmview.NamedObject;
import com.onpositive.realmview.basic.BasicRealmView;
import com.onpositive.realmview.model.IHasViews;
import com.onpositive.semantic.model.realm.IModifiableRealm;
import com.onpositive.semantic.model.realm.Realm;

public class ViewRealm extends Realm<IRealmView> implements IAdaptable{

	public void load(DataInputStream inputStream, IHasViews<?> hv) throws IOException {
		try {
			int count = inputStream.readInt();
			for (int a = 0; a < count; a++) {
				AbstractRealmView element = createView(hv);
				element.read(inputStream);
				add(element);
			}
		} finally {
			inputStream.close();
		}
	}

	@SuppressWarnings("unchecked")
	protected AbstractRealmView createView(IHasViews<?> hv) {
		return new BasicRealmView(
				(IModifiableRealm<? extends NamedObject>) this, hv);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void store(DataOutputStream outputStream) throws IOException {
		try {
			Collection<AbstractRealmView> rv = new ArrayList(getContents());
			outputStream.writeInt(rv.size());
			for (AbstractRealmView v : rv) {
				v.store(outputStream);
			}
		} finally {
			outputStream.close();
		}
	}

	@SuppressWarnings("rawtypes")
	public Object getAdapter(Class adapter) {
		return Platform.getAdapterManager().getAdapter(this, adapter);
	}
}
